const { HttpError } = require('../core/httpError.js');
const { dev } = require('../config/config.js');

const webError = async (ctx, next) => {
    try {
        await next();
    } catch (err) {
        const isHttpError = err instanceof HttpError;

        // if(dev && !isHttpError){
        //     throw err;
        // }

        if(isHttpError){ // 已知错误
            console.log('已知错误', isHttpError)

            ctx.body = {
                msg: err.msg,
                code: err.code,
                requestURL: `${ctx.request.header.origin}${ctx.originalUrl}`
            }
            ctx.status = err.status;
        } else { // 未知错误
            console.log('未知错误', err)

            ctx.body = {
                msg: '服务器出现未知错误',
                code: 500,
                error: err.toString(),
                requestURL: `${ctx.request.header.origin}${ctx.originalUrl}`
            }
            ctx.status = 500;
        }
    }
}

module.exports = webError;